import EchartsComponent from '@/components/EchartsComponent';
import { getEmptyOptions } from '@/dictionary';
import { statisticSocControllerGetSocData } from '@/services/ess/statisticBatterySoc';
import { useIntl } from '@umijs/max';
import { message, Spin } from 'antd';
import dayjs from 'dayjs';
import React, { useRef, useState } from 'react';
import ChartForm from './ChartForm';

type SocChartProps = {
  height?: number;
};

const SocChart: React.FC<SocChartProps> = ({ height = 340 }) => {
  const intl = useIntl();
  const [loading, setLoading] = useState(false);
  const [options, setOptions] = useState<any>({});
  const chartRef = useRef(null);

  const submitForm = async (value: any) => {
    if (!value?.code || !value?.code?.length) {
      message.warning(intl.formatMessage({ id: 'statistics.analyze.objWarning' }));
      return;
    }
    if (value?.code?.length > 100) {
      message.warning(intl.formatMessage({ id: 'statistics.analyze.objWarning100' }));
      return;
    }

    setLoading(true);
    try {
      const params = {
        startDate: dayjs(value.date).format('YYYY-MM-DD'),
        codes: Array.isArray(value.code) ? value.code : [value.code],
        interval: value.interval || 30,
      };

      const res = await statisticSocControllerGetSocData(params);

      if (res?.success) {
        chartRef?.current?.instance()?.clear();

        if (!res.data?.xaxis?.length || !res.data?.yaxis?.length) {
          setOptions(getEmptyOptions());
          setLoading(false);
          return;
        }

        const newOptions = {
          tooltip: {
            trigger: 'axis',
            confine: true,
            formatter: function (params: any[]) {
              let text = `<div>${params[0].axisValueLabel}<br/>`;
              (params || []).forEach((item) => {
                text += `${item.marker}${item.seriesName}&nbsp;:&nbsp;
                ${item.value ?? ''}${
                  item.value !== undefined && item.value !== null ? '%' : ''
                }&nbsp;&nbsp;&nbsp;&nbsp;<br/>`;
              });
              text += '</div>';
              return text;
            },
          },
          legend: {
            type: 'scroll',
            orient: 'horizontal',
            top: 5,
            right: 0,
          },
          grid: {
            left: 25,
            right: 5,
            top: 60,
            bottom: 15,
            containLabel: true,
            show: true,
            borderColor: 'transparent',
            backgroundColor: '#F8F9FA',
          },
          dataZoom: {
            type: 'inside',
          },
          xAxis: [
            {
              type: 'category',
              nameTextStyle: {
                color: '#222',
              },
              data: res.data.xaxis,
              axisTick: {
                alignWithLabel: true,
                show: true,
                inside: true,
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#ddd',
                },
              },
              axisLabel: {
                color: '#222',
                formatter: function (value: string) {
                  return value?.substring(11)?.substring(0, 5);
                },
              },
            },
          ],
          yAxis: [
            {
              type: 'value',
              name: `${intl.formatMessage({ id: 'bigdata.unitS' })}%`,
              nameTextStyle: {
                color: '#222',
                align: 'left',
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#ddd',
                },
              },
              axisTick: {
                show: true,
                inside: true,
              },
              splitLine: {
                show: true,
                lineStyle: {
                  type: 'dashed',
                },
              },
              axisLabel: {
                color: '#222',
              },
            },
          ],
          series: res.data.yaxis.map((item: any) => ({
            name: item.title,
            type: 'line',
            data: item.pointsValues?.length ? [...item.pointsValues] : [],
            smooth: true,
            symbol: 'none',
          })),
        };

        setOptions(newOptions);
      } else {
        chartRef?.current?.instance()?.clear();
        setOptions(getEmptyOptions());
      }
    } catch (error) {
      console.error('Error fetching SOC data:', error);
      chartRef?.current?.instance()?.clear();
      setOptions(getEmptyOptions());
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col">
      <ChartForm dateType={'date'} submitForm={submitForm} />
      <Spin spinning={loading}>
        <EchartsComponent ref={chartRef} option={options} height={height} />
      </Spin>
    </div>
  );
};

export default SocChart;
